// pagesProperty/pages/payslip/sign/index.js
var app = getApp(), fetchApi = require("../../../../utils/httpPost.js"),
formatTime = require("../../../../component/common.js");
import Toast from '../../../../component/vant/toast/toast';
import Dialog from '../../../../component/vant/dialog/dialog';

var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: true,
    hasData: false,
    pageIndex: 1,
    pageSize: 10,
    paySlipInfo:[],
    slipId:0,
    user_id:0,
    fromType: 0,
    signImg:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id){
      this.data.slipId = options.id;
    }
    
    if(options.from){
      this.data.fromType = options.from;
    }
    this.data.user_id = app.getStorageSync("user_id");
    this.onHttpInit();
    this.startCanvas();
  },

  onHttpInit: function () {
    var that = this;
    let dataParam = {};
    let url = '/estate/paySlip/last/detail';
    if(this.data.fromType == 1){
      url = '/estate/paySlip/detail';
      dataParam = {
        slipId: that.data.slipId
      }
    }
    fetchApi.httpPost(url, dataParam, function (res) {
      console.log("获取工资条信息", res)
      if (res.data.code == 0) {
        that.data.slipId = res.data.data.paySlip.id;
        that.setData({
          hasData: true,
          paySlipInfo: res.data.data.paySlip
        })
      }else{
        Toast.fail(res.data.msg)
      }
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
      that.setData({ netWork: true, loading: true,  isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false,loading: true,  isLoading: false, })
    })
  },


  

    /**
    * 以下 - 手写签名 / 上传签名
    */
  startCanvas: function () {//画布初始化执行
    var that = this;
    //获取系统信息
    let windownInfo= wx.getWindowInfo();
    console.log('窗口信息', windownInfo)
    canvasw = windownInfo.windowWidth;
    canvash = windownInfo.windowHeight;
    that.setData({ canvasw: canvasw });
    that.setData({ canvash: canvash });

    this.initCanvas();
    this.cleardraw(); 
  },
  //初始化函数
  initCanvas: function () {
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.fillStyle = 'rgba(255, 255, 255, 0)';
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    }
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      }
    }
    context.clearRect(0, 0, canvasw, canvash);
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  //清除画布
  cleardraw: function () {
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
  uploadSignImg(){
      var that = this
      //生成图片
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        //设置输出图片的宽高
        // destWidth:150, 
        // destHeight:150,
        // fileType:'jpg',
        quality:1.0,
        success: function (res) {
          console.log(res)
          // canvas图片地址 res.tempFilePath
          that.data.signImg = res.tempFilePath;
          wx.uploadFile({
            url: fetchApi.getPlatformUrl() + '/estate/paySlip/uploadSignImg',
            filePath: res.tempFilePath,
            name: 'file',
            formData: {
              user_id: that.data.user_id,
              slip_id: that.data.slipId,
            },
            success: function (res) {
              console.log('uploadFile success res', res);
              var dataJson = JSON.parse(res.data);
              if(dataJson.code == 0){
                Toast(dataJson.msg);
                setTimeout(function(){
                  wx.navigateBack({
                    delta: -1
                  })
                }, 500);
              }else{
                Toast(dataJson.msg);
              }
              console.log('that.data.signImg',that.data.signImg)
            },
            fail: function (res) {
              console.log('uploadFile fail res', res)
            }
          })

        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
            showCancel: false
          });
        },
        complete: function () {}
      })
  }
})